package be.bonamis.umpire.ui.client.mvp.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import be.bonamis.projects.umpire.business.dto.AnswerDTO;
import be.bonamis.projects.umpire.business.dto.IndividualResultDTO;
import be.bonamis.projects.umpire.business.dto.PersonResultDTO;
import be.bonamis.projects.umpire.business.dto.QuestionDTO;
import be.bonamis.projects.umpire.business.dto.QuestionStatDTO;
import be.bonamis.projects.umpire.business.dto.QuizDTO;
import be.bonamis.projects.umpire.business.dto.QuizStatsDTO;
import be.bonamis.projects.umpire.business.dto.ResponseStyle;
import be.bonamis.projects.umpire.business.dto.UmpireDTO;
import be.bonamis.umpire.ui.client.mvp.QuizView;
import be.bonamis.umpire.ui.client.resources.Resources;

import com.google.gwt.cell.client.ActionCell;
import com.google.gwt.cell.client.DateCell;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.IdentityColumn;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.ListDataProvider;
import com.google.inject.Inject;

public class QuizViewImpl extends Composite implements QuizView {

	private Presenter presenter;
	private UmpireDTO umpire;
	private List<QuizDTO> quizs;
	private QuizDTO quiz;
	private QuizStatsDTO stats;
	private IndividualResultDTO personResult;

	interface QuizViewImplUiBinder extends UiBinder<HTMLPanel, QuizViewImpl> {
	}

	public interface MyStyle extends CssResource {
		String wrongAnswer();
		String rightAnswer();
	}

	@UiField
	protected MyStyle style;

	@UiField
	CellTable<QuizDTO> quizListTable;

	@UiField
	CellTable<PersonResultDTO> personResultsTable;

	@UiField
	CellTable<QuestionStatDTO> questionStatsTable;

	@UiField
	VerticalPanel quizPanel;

	@UiField
	Button validateButton;
	
	@UiField
	Anchor dispoButton;
	
	@UiField
	Anchor whoButton;
	
	@UiField
	Anchor quizButton;
	
	@UiField
	Anchor historyButton;
	
	@UiField
	Label fullName;
	
	@UiField
	SimplePanel simplePanel;
	
	@UiHandler("dispoButton")
	public void onClickDispo(ClickEvent event) {
		presenter.dispoButtonClicked();
	}
	
	@UiHandler("whoButton")
	public void onClickWho(ClickEvent event) {
		presenter.whoButtonClicked();
	}	
	
	@UiHandler("historyButton")
	public void onClickHistory(ClickEvent event) {
		//presenter.historyButtonClicked();
	}
	
	@UiHandler("quizButton")
	public void onClickQuiz(ClickEvent event) {
		quizListTable.setVisible(true);
		personResultsTable.setVisible(false);
		questionStatsTable.setVisible(false);
		quizTable.setVisible(false);
		validateButton.setVisible(false);
	}

	private ListDataProvider<QuizDTO> quizDataProvider;
	private ListDataProvider<PersonResultDTO> personResultsDataProvider;
	private ListDataProvider<QuestionStatDTO> questionStatsDataProvider;

	final List<CheckBox> checkboxes = new ArrayList<CheckBox>();
	final List<Boolean> corrects = new ArrayList<Boolean>();

	DateTimeFormat quizDaysFormat = DateTimeFormat.getFormat("dd MMMM yyyy");

	FlexTable quizTable;
	final Integer COLUMN_QUESTION = 0;
	final Integer COLUMN_ANSWER = 1;
	final Integer COLUMN_CHECKBOX = 2;

	@Inject
	public QuizViewImpl(QuizViewImplUiBinder uiBinder, final Resources resources) {
		initWidget(uiBinder.createAndBindUi(this));
		resources.css().ensureInjected();
		postInit();

		quizPanel.clear();

		DateCell dateCell = new DateCell(quizDaysFormat);
		Column<QuizDTO, Date> dateColumn = new Column<QuizDTO, Date>(dateCell) {
			@Override
			public Date getValue(QuizDTO object) {
				return object.getDay();
			}
		};
		quizListTable.addColumn(dateColumn);

		ActionCell<QuizDTO> participateCell = new ActionCell<QuizDTO>("Participate",
				new ActionCell.Delegate<QuizDTO>() {
					@Override
					public void execute(QuizDTO dto) {
						quizListTable.setVisible(false);
						presenter.getQuizById(dto.getId());						
					}
				});		
		
		IdentityColumn<QuizDTO> particpateCellColumn = new IdentityColumn<QuizDTO>(participateCell);
		quizListTable.addColumn(particpateCellColumn);

		ActionCell<QuizDTO> showStatCell = new ActionCell<QuizDTO>("Show Quiz stats",
				new ActionCell.Delegate<QuizDTO>() {
					@Override
					public void execute(QuizDTO dto) {
						quizListTable.setVisible(false);
						personResultsTable.setVisible(true);
						questionStatsTable.setVisible(true);
						presenter.showStatsTable(dto.getId());
					}
				});
		IdentityColumn<QuizDTO> statsCellColumn = new IdentityColumn<QuizDTO>(showStatCell);
		quizListTable.addColumn(statsCellColumn);

		quizDataProvider = new ListDataProvider<QuizDTO>();
		quizDataProvider.addDataDisplay(quizListTable);

		TextColumn<PersonResultDTO> personColumn = new TextColumn<PersonResultDTO>() {
			@Override
			public String getValue(PersonResultDTO dto) {
				return dto.getFullName();
			}
		};
		TextColumn<PersonResultDTO> resultColumn = new TextColumn<PersonResultDTO>() {
			@Override
			public String getValue(PersonResultDTO dto) {
				return Integer.toString(dto.getScore());
			}
		};
		personResultsTable.addColumn(personColumn, "Nom de l'arbitre");
		personResultsTable.addColumn(resultColumn, "Score");

		TextColumn<QuestionStatDTO> questionColumn = new TextColumn<QuestionStatDTO>() {
			@Override
			public String getValue(QuestionStatDTO dto) {
				return dto.getQuestion();
			}
		};
		TextColumn<QuestionStatDTO> statColumn = new TextColumn<QuestionStatDTO>() {
			@Override
			public String getValue(QuestionStatDTO dto) {
				NumberFormat percentFormat = NumberFormat.getPercentFormat();
				percentFormat.overrideFractionDigits(0);
				String result = percentFormat.format(1-(float) dto.getResult()
						/ stats.getPersonResults().size());
				return result;
			}
		};
		questionStatsTable.addColumn(questionColumn, "Libellé de la question");
		questionStatsTable.addColumn(statColumn, "Taux d'échec");

		personResultsDataProvider = new ListDataProvider<PersonResultDTO>();
		personResultsDataProvider.addDataDisplay(personResultsTable);
		questionStatsDataProvider = new ListDataProvider<QuestionStatDTO>();
		questionStatsDataProvider.addDataDisplay(questionStatsTable);
	}

	private void postInit() {
		String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName();
		if (currentLocale.equals("default")) {
			currentLocale = "fr";
		}
		String[] localeNames = LocaleInfo.getAvailableLocaleNames();
		for (String localeName : localeNames) {
			if (!localeName.equals("default")) {
			}
		}
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

	@Override
	public Presenter getPresenter() {
		return presenter;
	}

	@Override
	public void setQuiz(QuizDTO quizDTO) {
		this.quiz = quizDTO;
		//Label title = new Label("Title of the Quiz");
		//quizPanel.add(title);
		quizPanel.add(this.createCellTable(quizDTO));
		validateButton.setVisible(true);
	}

	private FlexTable createCellTable(QuizDTO quizDTO) {
		quizTable = new FlexTable();
		int row = 0;
		for (QuestionDTO questionDTO : quiz.getQuestions()) {
			quizTable.setText(row, COLUMN_QUESTION, questionDTO.getQuestionFr());
			for (AnswerDTO answerDTO : questionDTO.getAnswers()) {
				quizTable.setText(row, COLUMN_ANSWER, answerDTO.getAnswerFr());
				quizTable.getRowFormatter().addStyleName(row, "gwt-flexTable-tr");
				CheckBox checkBoxRow = new CheckBox();
				checkboxes.add(checkBoxRow);
				quizTable.setWidget(row, COLUMN_CHECKBOX, checkBoxRow);
				quizTable.getCellFormatter().addStyleName(row, COLUMN_CHECKBOX, "center");
				row++;
			}
		}
		return quizTable;
	}

	@Override
	public void setValues(UmpireDTO umpire, List<QuizDTO> quizs) {
		this.umpire = umpire;
		this.quizs = quizs;
		fullName.setText(umpire.getFirstName() +" " + umpire.getLastName());

		quizDataProvider.getList().clear();
		List<QuizDTO> list = quizDataProvider.getList();
		for (QuizDTO quizDTO : quizs) {
			list.add(quizDTO);
		}
	}

	@UiHandler("validateButton")
	void onClickToValidate(ClickEvent event) {
		event.preventDefault();
		presenter.putResponsesInDB(umpire.getId(), quiz.getId(), checkboxes);
		System.out.println("Score: " + personResult.getScore() + " on " + quiz.getQuestions().size());
	}

	@Override
	public void setQuizStats(QuizStatsDTO quizStatsDTO) {
		this.stats = quizStatsDTO;
		personResultsTable.setVisible(true);
		questionStatsTable.setVisible(true);

		personResultsDataProvider.getList().clear();
		List<PersonResultDTO> prs = personResultsDataProvider.getList();
		for (PersonResultDTO personResultDTO : quizStatsDTO.getPersonResults()) {
			prs.add(personResultDTO);
		}

		questionStatsDataProvider.getList().clear();		
		List<QuestionStatDTO> qss = questionStatsDataProvider.getList();
		for (QuestionStatDTO questionStatDTO : quizStatsDTO.getQuestionStats()) {
			qss.add(questionStatDTO);
		}
	}

	@Override
	public void setPersonResult(IndividualResultDTO prDTO) {
		this.personResult = prDTO;
		for (int row = 0; row < personResult.getStyles().length; row++) {
			if (personResult.getStyles()[row] == ResponseStyle.WRONG) {
				quizTable.getCellFormatter().addStyleName(row, COLUMN_ANSWER, style.wrongAnswer());
			} else {
				if (personResult.getStyles()[row] == ResponseStyle.RIGHT) {
					quizTable.getCellFormatter().addStyleName(row, COLUMN_ANSWER,
							style.rightAnswer());
				}
			}
			checkboxes.get(row).setEnabled(false);
			if (personResult.getResponses().get(row) == 1) {
				checkboxes.get(row).setValue(true);
			}			
		}
		validateButton.setEnabled(false);
	}
	
	@Override
	public UmpireDTO getUmpire() {
		return umpire;
	}

	@Override
	public QuizDTO getQuiz() {
		return quiz;
	}
}
